class TransferProcessExplanation:
    def __init__(self, source_features, target_features, source_labels, target_predictions):
        self.source_features = source_features
        self.target_features = target_features
        self.source_labels = source_labels
        self.target_predictions = target_predictions
        
    def visualize_domain_alignment(self):
        """可视化域对齐效果"""
        # 使用t-SNE降维
        combined_features = np.vstack([self.source_features, self.target_features])
        tsne = TSNE(n_components=2, random_state=42)
        embedded = tsne.fit_transform(combined_features)
        
        # 创建域标签
        source_domain = np.zeros(len(self.source_features))
        target_domain = np.ones(len(self.target_features))
        domain_labels = np.concatenate([source_domain, target_domain])
        
        plt.figure(figsize=(15, 6))
        
        # 域分布
        plt.subplot(1, 2, 1)
        scatter = plt.scatter(embedded[:, 0], embedded[:, 1], c=domain_labels, 
                            cmap='coolwarm', alpha=0.7)
        plt.colorbar(scatter, ticks=[0, 1])
        plt.title('Domain Distribution (Source=0, Target=1)')
        
        # 类别分布
        plt.subplot(1, 2, 2)
        combined_labels = np.concatenate([
            self.source_labels, 
            np.argmax(self.target_predictions, axis=1)
        ])
        scatter = plt.scatter(embedded[:, 0], embedded[:, 1], c=combined_labels, 
                            cmap='viridis', alpha=0.7)
        plt.colorbar(scatter)
        plt.title('Class Distribution')
        
        plt.tight_layout()
        plt.show()
    
    def analyze_feature_distribution(self):
        """分析特征分布差异"""
        from scipy.spatial.distance import jensenshannon
        
        # 计算特征分布差异
        distribution_differences = []
        for i in range(self.source_features.shape[1]):
            source_dist = np.histogram(self.source_features[:, i], bins=50, density=True)[0]
            target_dist = np.histogram(self.target_features[:, i], bins=50, density=True)[0]
            js_distance = jensenshannon(source_dist, target_dist)
            distribution_differences.append(js_distance)
        
        # 可视化分布差异
        plt.figure(figsize=(12, 6))
        plt.bar(range(len(distribution_differences)), distribution_differences)
        plt.title('Feature Distribution Differences (Jensen-Shannon Distance)')
        plt.xlabel('Feature Index')
        plt.ylabel('JS Distance')
        plt.show()
        
        return distribution_differences
    
    def calculate_transfer_metrics(self):
        """计算迁移性能指标"""
        from sklearn.metrics import accuracy_score, f1_score
        

        # 这里使用伪标签进行评估
        target_pred_labels = np.argmax(self.target_predictions, axis=1)
        
        metrics = {
            'source_accuracy': accuracy_score(self.source_labels, 
                                            np.argmax(self.source_features, axis=1)),
            'target_confidence': np.mean(np.max(self.target_predictions, axis=1)),
            'domain_alignment': self._calculate_domain_alignment(),
            'feature_similarity': self._calculate_feature_similarity()
        }
        
        return metrics
    
    def _calculate_domain_alignment(self):
        """计算域对齐程度"""
        from sklearn.svm import LinearSVC
        from sklearn.model_selection import cross_val_score
        
        # 构建域分类任务
        X_domain = np.vstack([self.source_features, self.target_features])
        y_domain = np.concatenate([np.zeros(len(self.source_features)), 
                                 np.ones(len(self.target_features))])
        
        # 训练域分类器
        clf = LinearSVC()
        scores = cross_val_score(clf, X_domain, y_domain, cv=5)
        
        # 域分类准确率越低，说明对齐越好
        return 1 - np.mean(scores)
    
    def _calculate_feature_similarity(self):
        """计算特征相似度"""
        from scipy.spatial.distance import cosine
        
        source_mean = np.mean(self.source_features, axis=0)
        target_mean = np.mean(self.target_features, axis=0)
        
        return 1 - cosine(source_mean, target_mean)

# 迁移过程分析示例

transfer_analyzer = TransferProcessExplanation(
    source_features=X_train,
    target_features=X_target_processed,  # 处理后的目标域特征
    source_labels=y_train,
    target_predictions=target_predictions
)

# 可视化域对齐
transfer_analyzer.visualize_domain_alignment()

# 分析特征分布差异
distribution_differences = transfer_analyzer.analyze_feature_distribution()

# 计算迁移指标
transfer_metrics = transfer_analyzer.calculate_transfer_metrics()
print("Transfer Metrics:", transfer_metrics)
